<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>渐变</title>
  <link rel="icon" href="https://img.kaikeba.com/kkb_portal_icon.ico">
  <style>
    body {
      margin: 0;
      overflow: hidden;
    }

    #canvas {
      background-color: antiquewhite;
    }
  </style>
</head>

<body>
  <canvas id="canvas"></canvas>
  <!-- 顶点着色器 -->
  <script id="vertexShader" type="x-shader/x-vertex">
    attribute vec4 a_Position;
    void main(){
      gl_Position=a_Position;
    }
  </script>
  <!-- 片元着色器 -->
  <script id="fragmentShader" type="x-shader/x-fragment">
    precision mediump float;

    uniform vec4 u_Color0;
    uniform vec4 u_Color1;
    vec4 c01=u_Color1-u_Color0;

    uniform vec2 u_Start;
    uniform vec2 u_End;
    vec2 se=u_End-u_Start;
    float seLen=length(se);
    vec2 normal=normalize(se);

    void main(){
      vec2 sf=vec2(gl_FragCoord)-u_Start;
      float fsLen=clamp(dot(sf,normal),0.0,seLen);
      float ratio=fsLen/seLen;
      gl_FragColor=u_Color0+c01*ratio;
    }
  </script>
  <script type="module">
    import { initShaders } from "../jsm/Utils.js";
    import Poly from './jsm/Poly.js'

    const canvas = document.querySelector("#canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    // 获取着色器文本
    const vsSource = document.querySelector("#vertexShader").innerText;
    const fsSource = document.querySelector("#fragmentShader").innerText;

    //三维画笔
    const gl = canvas.getContext("webgl");

    //初始化着色器
    //功能：解析着色器文本，整合到程序对象里，关联webgl上下文对象，实现两种语言的相互通信
    initShaders(gl, vsSource, fsSource);


    //声明颜色 rgba
    gl.clearColor(0, 0, 0, 1);

    const source = new Float32Array([
      -1, 1,
      -1, -1,
      1, 1,
      1, -1
    ]);

    const rect = new Poly({
      gl,
      source,
      type: 'TRIANGLE_STRIP',
      attributes: {
        a_Position: {
          size: 2,
          index: 0
        }
      },
      uniforms: {
        u_Start: {
          type: 'uniform2fv',
          //value: [canvas.width * 0.25, canvas.height * 0.75]
          value: [canvas.width * 0.4, 0]
        },
        u_End: {
          type: 'uniform2fv',
          //value: [canvas.width * 0.75, canvas.height * 0.25]
          value: [canvas.width * 0.6, 0]
        },
        u_Color0: {
          type: 'uniform4fv',
          value: [1, 0, 1, 1]
        },
        u_Color1: {
          type: 'uniform4fv',
          value: [1, 1, 0, 1]
        },
      }
    })

    gl.clear(gl.COLOR_BUFFER_BIT);
    rect.draw()

  </script>
</body>

</html>